<?php
namespace Modules\Skinov\Services;

use Modules\Skinov\Models\UserWechatModel;

class UserWechatService {
  public function createByOpenidHasPid($openid, $data = [], $pid = null) {
    if(is_null($pid)) { $pid = 0; }

    $res = (new UserService()) -> create([
      'pid' => $pid,
      'account' => rand(10000000, 99999999)
    ]);

    if($res['code'] !== 0) { return $res; }

    if(isset($data['user_wallet'])) {
      $data['user_wallet'] = array_merge(['id' => $res['model'] -> id], $data['user_wallet']);
    } else {
      $data['user_wallet'] = [
        'id' => $res['model'] -> id,
        'openid' => $openid
      ];
    }

    return $this -> create($data['user_wallet']);
  }

  public function create($data) {
    $model = new UserWechatModel($data);
    if(!$model -> create()) {
      $messages = $model -> getMessages();
      return ['code' => -1, 'msg' => $messages[0] -> getMessage()];
    }

    return ['code' => 0, 'model'=>$model];
  }

  public function findFirstByOpenidHasPid($openid, $data = [], $pid = null) {
    $res = $this -> findFirst(['conditions'=>'openid = "' . $openid . '"']);
    if($res['code'] != 0) { return $this -> createByOpenidHasPid($openid, $data, $pid); }

    return ['code'=>0,'model'=>$res['model']];
  }

  public function findFirst($parameters = []) {
    $model = UserWechatModel::findFirst($parameters);
    if(!$model) { return ['code' => -1, 'msg' => '数据不存在或已删除']; }

    return ['code' => 0, 'model'=>$model];
  }
}
